<?php
namespace app\api\controller\paotui\poster;
use addons\paotui\service\Config as PaotuiConfig;
use app\admin\model\paotui\Poster;
use app\common\exception\UploadException;
use app\common\library\Sms as Smslib;
use app\common\library\Upload;
use think\Hook;
/** * 通用接口 */
class Common extends PosterApi{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['xieyi','send_sms','check_sms','upload'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = "*";
    public function _initialize()
    { 
	parent::_initialize();
    }
    /**
	* 获取合作协议
	*/
    public function xieyi(){
        $this->success("请求成功",PaotuiConfig::get('xieyi'));
	}
    /**
	* 上传文件
	* @ApiMethod (POST)     * @param File $file 文件流
	*/
    public function upload()
    {
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
		} catch (UploadException $e) {
            $this->error($e->getMessage());
		}
        $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
	}
    /**
	* 发送验证码
	*     
	* @param string $mobile 手机号
	* @param string $event 事件名称
	*/
    public function send_sms()
    {
        $mobile = $this->request->post("mobile");
        $event = $this->request->post("event");
        $event = $event ? $event : 'mobilelogin';
        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
		}
        $last = Smslib::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('发送频繁'));
		}
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('发送频繁'));
		}
        if ($event) {
            $posterModel = new Poster();
            $posterInfo = $posterModel->where(['mobile'=>$mobile])->find();
            if (empty($posterInfo)) {
                $this->error(__('当前手机号码还未注册快递员'));
			}
		}
        if (!Hook::get('sms_send')) {
            $this->error(__('请在后台插件管理安装短信验证插件'));
		}
        $ret = Smslib::send($mobile, null, $event);
        if ($ret) {
            $this->success(__('发送成功'));
		} else {
            $this->error(__('发送失败，请检查短信配置是否正确'));
		}
	}
}